package com.lcredu.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author 黎长容
 * @date 2025-07-24 23:06
 */
@Controller
@RequestMapping("/file")
public class FileHandle {

    /**
     * 黎长容知识:上传文件
     * 1. 引入commons-fileupload依赖
     * 2. 方法传参至少要有 @RequestParam("file") MultipartFile file 和 HttpServletRequest request
     * 3. 上传之后的文件就被 file 获取了,其原理还是之前的那个fileItem.write()把临时文件写入了复制的文件
     * 4. 获取文件目录为 String fileFullPath = request.getServletContext().getRealPath("/text/" + filename);
     * 5. 文件赋值包装方法是 file.transferTo(endFile);
     *
     * @param file    : 上传后的文件就是这个
     * @param request
     * @return
     */
    //文件上传
    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String filename = file.getOriginalFilename();
        System.out.println("接收到文件=" + filename);
        String fileFullPath = request.getServletContext().getRealPath("/text/" + filename);
        File endFile = new File(fileFullPath);
        //复制传进来的文件给这个文件
        file.transferTo(endFile);
        return "success";
    }
}
